import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: LoginView  
    },
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      children: [
        // 子路由
        {
          path: 'lists',
          name: 'lists',
          component: () => import('../views/ListsView.vue')
        },
        {
          path: 'add',
          name: 'add',
          component: () => import('../views/AddView.vue')
        },
        {
          path: 'edit/:id',
          name: 'edit',
          component: () => import('../views/EditView.vue')
        }
      ]
    },
  ]
})

router.beforeEach((to, from, next) => {
  // 登录验证
  const isLogin = localStorage.getItem('isLogin')
  if (isLogin) {
    next()
  } else {
    if (to.name !== 'login') {
      alert('请先登录')
      next('/login')
    } else {
      next()
    }
  }
})
export default router

